package com.lyj.friend.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lyj.common.core.constants.CacheConstants;
import com.lyj.common.core.constants.Constants;
import com.lyj.common.core.enums.ExamListType;
import com.github.pagehelper.PageHelper;
import com.lyj.common.core.enums.ResultCode;
import com.lyj.friend.domain.exam.Exam;
import com.lyj.friend.domain.exam.ExamQuestion;
import com.lyj.friend.domain.exam.dto.ExamQueryDTO;
import com.lyj.friend.domain.exam.vo.ExamVO;
import com.lyj.friend.mapper.exam.ExamMapper;
import com.lyj.friend.mapper.exam.ExamQuestionMapper;
import com.lyj.friend.mapper.user.UserExamMapper;
import com.lyj.redis.service.RedisService;
import com.lyj.security.exception.ServiceException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LIUYANJIAO
 * Date: 2025-09-05
 * Time: 23:31
 */
@Component
public class ExamCacheManager {
    @Autowired
    private RedisService redisService;

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private ExamQuestionMapper examQuestionMapper;


    public Long getListSize(Integer type, Long userId) {
        String examListKey = getExamListKey(type,userId);
        //通过key查询redis获得数据
        return redisService.getListSize(examListKey);
    }

    private String getExamListKey(Integer type, Long userId) {
        //通过不同的 type返回不同的key
        if(ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(type)){
            //未结束
            return CacheConstants.EXAM_UNFINISHED_LIST;
        }else if(ExamListType.EXAM_HISTORY_LIST.getValue().equals(type)){
            //历史列表
            return CacheConstants.EXAM_HISTORY_LIST;
        }else {
            //访问用户的所有列表
            return CacheConstants.USER_EXAM_LIST + userId;
        }
    }

    public void refreshCache(Integer type, Long userId) {
        List<Exam> examList = new ArrayList<>();
        if(ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(type)){
            //未完赛
            //查询数据库中的数据
            examList = examMapper.selectList(new QueryWrapper<Exam>().lambda()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .gt(Exam::getEndTime, LocalDateTime.now())
                    .eq(Exam::getStatus, Constants.TRUE)
                    .orderByDesc(Exam::getCreateTime));
        }else if(ExamListType.EXAM_HISTORY_LIST.getValue().equals(type)){
            //历史竞赛
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .le(Exam::getEndTime, LocalDateTime.now())
                    .eq(Exam::getStatus, Constants.TRUE)
                    .orderByDesc(Exam::getCreateTime));
        }else if(ExamListType.USER_EXAM_LIST.getValue().equals(type)){
            List<ExamVO> examVOList = userExamMapper.selectUserExamList(userId);
            BeanUtils.copyProperties(examVOList,examList);
        }
        if (CollectionUtil.isEmpty(examList)){
            return;
        }
        //每个竞赛的详细信息
        Map<String,Exam> examMap = new HashMap<>();
        //列表中竞赛的id
        List<Long> examIdList = new ArrayList<>();
        for(Exam exam: examList){
            examMap.put(getDetailKey(userId),exam);
            examIdList.add(exam.getExamId());
        }
        redisService.multiSet(examMap);//刷新详情缓存
        //删除后重新加载，以达到刷新的目的
        redisService.deleteObject(getExamListKey(type,userId));
        redisService.rightPushAll(getExamListKey(type,userId),examIdList);
    }
    private String getDetailKey(Long examId) {
        return CacheConstants.EXAM_DETAIL + examId;
    }

    public List<ExamVO> getExamVOList(ExamQueryDTO examQueryDTO, Long userId) {
        //手动进行分页操作
        int start = (examQueryDTO.getPageNum() - 1) * examQueryDTO.getPageSize();
        int end = start + examQueryDTO.getPageSize() - 1; //下标需要 -1
        String examListKey = getExamListKey(examQueryDTO.getType(),userId);
        List<Long> examIdList = redisService.getCacheListByRange(examListKey, start, end, Long.class);
        List<ExamVO> examVOList = assembleExamVOList(examIdList);
        if(CollectionUtil.isEmpty(examVOList)){
            //说明redis中的数据有问题，应该从数据库中重新刷新
            examVOList = getExamListByDB(examQueryDTO,userId);
            refreshCache(examQueryDTO.getType(), userId);
        }
        return examVOList;
    }

    private List<ExamVO> getExamListByDB(ExamQueryDTO examQueryDTO, Long userId) {
        PageHelper.startPage(examQueryDTO.getPageNum(),examQueryDTO.getPageSize());
        if(ExamListType.USER_EXAM_LIST.getValue().equals(examQueryDTO.getType())){
            return userExamMapper.selectUserExamList(userId);
        }else {
            return examMapper.selectExamList(examQueryDTO);
        }
    }

    private List<ExamVO> assembleExamVOList(List<Long> examIdList) {
        if(CollectionUtil.isEmpty(examIdList)){
            return null;
        }
        //将idList转化为idKeyList
        List<String> idKeyList = new ArrayList<>();
        for(Long examId : examIdList){
            idKeyList.add(getDetailKey(examId));
        }
        List<ExamVO> examVOList = redisService.multiGet(idKeyList,ExamVO.class);
        CollUtil.removeNull(examVOList);
        if(CollectionUtil.isEmpty(examVOList) || examVOList.size() != examIdList.size()){
            //查询出错
            return null;
        }
        return examVOList;
    }

    public void addUserExamCache(Long userId, Long examId) {
        String userExamListKey = getUserExamListKey(userId);
        redisService.leftPushForList(userExamListKey, examId);
    }

    private String getUserExamListKey(Long userId) {
        return CacheConstants.USER_EXAM_LIST + userId;
    }

    public Long getExamQuestionListSize(Long examId) {
        String examQuestionListKey = getExamQuestionListKey(examId);
        return redisService.getListSize(examQuestionListKey);
    }

    private String getExamQuestionListKey(Long examId) {
        return CacheConstants.EXAM_QUESTION_LIST + examId;
    }

    public void refreshExamQuestionCache(Long examId) {
       //首先在数据库中找到数据
       List<ExamQuestion> examQuestionList = examQuestionMapper.selectList(new QueryWrapper<ExamQuestion>().lambda()
               .select(ExamQuestion::getQuestionId)
               .eq(ExamQuestion::getExamId,examId)
               .orderByDesc(ExamQuestion::getQuestionOrder));
       if(CollectionUtil.isEmpty(examQuestionList)){
           return;
       }
       List<Long> examQuestionIdList = examQuestionList.stream().map(ExamQuestion::getQuestionId).toList();
       redisService.rightPushAll(getExamQuestionListKey(examId),examQuestionIdList);
        //节省 redis缓存资源
        long seconds = ChronoUnit.SECONDS.between(LocalDateTime.now(),
                LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0));
        redisService.expire(getExamQuestionListKey(examId), seconds, TimeUnit.SECONDS);
    }

    public Long getFirstQuestion(Long examId) {
        return redisService.indexForList(getExamQuestionListKey(examId),0,Long.class);
    }

    public Long preQuestion(Long examId, Long questionId) {
        //首先先找到当前题目的下标
        Long index = redisService.indexOfForList(getExamQuestionListKey(examId),questionId);
        //判断临界值
        if(index == 0){
            throw new ServiceException(ResultCode.FAILED_FIRST_QUESTION);
        }
        //查找数据
        return redisService.indexForList(getExamQuestionListKey(examId), index - 1, Long.class);
    }

    public Long nextQuestion(Long examId, Long questionId) {
        Long index = redisService.indexOfForList(getExamQuestionListKey(examId), questionId);
        long lastIndex = getExamQuestionListSize(examId) - 1;
        if (index == lastIndex) {
            throw new ServiceException(ResultCode.FAILED_LAST_QUESTION);
        }
        return redisService.indexForList(getExamQuestionListKey(examId), index + 1, Long.class);
    }
}
